package com.idemon.springcloudserviceribbonhystrix;

import com.netflix.hystrix.contrib.metrics.eventstream.HystrixMetricsStreamServlet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.netflix.hystrix.EnableHystrix;
import org.springframework.cloud.netflix.hystrix.dashboard.EnableHystrixDashboard;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

@EnableHystrix
@EnableHystrixDashboard
@EnableDiscoveryClient
@SpringBootApplication
public class SpringCloudServiceRibbonHystrixApplication {

	public static void main(String[] args) {
		SpringApplication.run(SpringCloudServiceRibbonHystrixApplication.class, args);
	}

	@Autowired
	private RestTemplateBuilder restTemplateBuilder;
	@Bean
	@LoadBalanced
	RestTemplate restTemplate(){
		return restTemplateBuilder.build();
	}

	/**
	 * 这里由于使用的spring-boot2.0，
	 * 需要添加 HystrixMetricsStreamServlet，
	 * 因为springboot的默认接收请求的路径不是 "/hystrix.stream"，
	 * 因此，在打开hystrix dashboard会报错：
	 * Unable to connect to Command Metric Stream；
	 * 只要在自己的项目里配置上HystrixMetricsStreamServlet就可以了;
	 * 或者在web.xml中添加该servlet配置也可
	 * @return
	 */
	@Bean
	public ServletRegistrationBean getServlet() {
		HystrixMetricsStreamServlet streamServlet = new HystrixMetricsStreamServlet();
		ServletRegistrationBean registrationBean = new ServletRegistrationBean(streamServlet);
		registrationBean.setLoadOnStartup(1);
		registrationBean.addUrlMappings("/hystrix.stream");
		registrationBean.setName("HystrixMetricsStreamServlet");
		return registrationBean;
	}
}
